#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/12 11:22
# @Author  : hhr
import requests, json, time
from administrative.models import OpLogs




class RecordAndPush():
    def __init__(self):
        pass

    def MessagePush(self, touser, title, applicant, ApplicationTime, SubjectMatter):
        """
        小程序订阅消息推送
        :param touser: 接收者Openid
        :param title: 流程名称
        :param applicant: 申请人
        :param ApplicationTime: 申请时间
        :param SubjectMatter: 申请事由
        :return:
        """
        if touser:
            # ========================== 获取access_token ========================================
            headers = {"Accept": "application/json", }
            reql = requests.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc669281d321d4ed1&secret=371945c837b88a952c1883b7c11b3ead", headers=headers)
            access_token = reql.json()["access_token"]

            # # ========================== 消息推送 ========================================
            url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}"
            params = {
                'touser': touser,  # 目标用户openid
                'template_id': 'ttZzMQiy13STJquLfqB7bwVw8MDbxZudiwYOAJHQbL8',  # 模版ID
                'page': "/pages/index/index",
                'miniprogram_state': 'trial',
                'data': {
                    'phrase3': {'value': title},
                    'name1': {'value': applicant},
                    'date2': {'value': ApplicationTime},
                    'thing4': {'value': SubjectMatter}
                }
            }
            real = requests.post(url, data=json.dumps(params))

    def OperationRecords(self, request, flow_name):
        """
        操作记录存储
        :param request:
        :return:
        """
        # 请求IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            # 如果有代理，获取真实IP
            re_ip = x_forwarded_for.split(",")[0]
        else:
            re_ip = request.META.get('REMOTE_ADDR')

        re_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())  # 请求时间（北京）

        # 请求方法
        re_method = request.method

        # 请求参数
        re_content = request.GET if re_method == 'GET' else request.POST
        if re_content:
            re_content = json.dumps(re_content)
        else:
            re_content = None

        OpLogs.objects.create(
            re_time=re_time,
            re_user=request.user.job_number,
            re_ip=re_ip,
            re_url=request.path,
            re_method=re_method,
            re_content=re_content,
            flow_name=flow_name
        )
